package com.junko.admin.controller.back;

import com.github.pagehelper.PageInfo;
import com.junko.admin.controller.BaseBackendController;
import com.junko.admin.tool.ToolIDEA;
import com.junko.core.constant.ConstantWebContext;
import com.junko.core.tool.PasswordEncoder;
import com.junko.core.tool.ToolDateTime;
import com.junko.core.tool.ToolPassword;
import com.junko.core.tool.ToolWeb;
import com.junko.model.JsonResult;
import com.junko.model.PageForm;
import com.junko.model.back.Admin;
import com.junko.model.query_helper.AdminQueryHelper;
import com.junko.service.back.IAdminService;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("/b/admin")
public class AdminController extends BaseBackendController {
    private static final Logger logger = LogManager.getLogger(AdminController.class);

    @Resource
    private IAdminService adminService;

    @RequestMapping
    public String index() {
        return "/back/admin/index";
    }

    /**
     * 分页
     */
    @RequestMapping("/page")
    public @ResponseBody
    Map page(AdminQueryHelper queryHelper,String createBegin,String createEnd) {
        Map<String,Object> params = new HashMap<>();
        if (StringUtils.isNotBlank(createBegin)) {
            queryHelper.setGmtCreateBegin(ToolDateTime.getDateByPlusDays(createBegin, ToolDateTime.pattern_ymd, 0));
        }
        if (StringUtils.isNotBlank(createEnd)) {
            queryHelper.setGmtCreateEnd(ToolDateTime.getDateByPlusDays(createEnd, ToolDateTime.pattern_ymd, 0));
        }
        PageInfo<Admin> pageInfo = adminService.pageFindModel("com.junko.dao.back.AdminDao.page", new PageForm(queryHelper), queryHelper);
        Map map = new HashMap();
        map.put("rows", pageInfo.getList());
        map.put("total", pageInfo.getTotal());
        return map;
    }

    /**
     * 添加
     */
    @RequestMapping("add")
    public String add() {
        return "/back/admin/add";
    }

    /**
     * 保存
     */
    @RequestMapping("save")
    public @ResponseBody
    JsonResult save(Admin admin, HttpServletResponse response) {
        try {
            Admin temp = adminService.findByAccount(admin.getAccount());
            if (temp != null && !equals(admin.getId(), temp.getId())) {
                return fail("账号[" + admin.getAccount() + "]已存在");
            }
            temp = adminService.findByNickname(admin.getNickname());
            if (temp != null && !equals(admin.getId(), temp.getId())) {
                return fail("昵称[" + admin.getNickname() + "]已存在");
            }
            admin.setSalt(PasswordEncoder.createSalt(16));
            admin.setPassword(ToolPassword.getEncPassword(admin.getSalt(), admin.getPassword()));
            // 初始化idea密钥
            admin.setIdea(Base64.encodeBase64String(ToolIDEA.initKey()));
            admin.setCreatorId(getCurrentAdminId(response));
            if (!adminService.insertSelective(admin)) {
                return fail();
            }
            return success();
        } catch (Exception e) {
            e.printStackTrace();
            return fail();
        }
    }

    /**
     * 编辑
     */
    @RequestMapping("edit")
    public String edit() {
        setAttr("admin", adminService.selectByPrimaryKey(getParaToLong("id")));
        return "/back/admin/edit";
    }

    /**
     * 更新
     */
    @RequestMapping("update")
    public @ResponseBody
    JsonResult update(Admin admin, HttpServletResponse response) {
        Admin old = adminService.selectByPrimaryKey(admin.getId());
        Admin temp = adminService.findByNickname(admin.getNickname());
        if (temp != null && !equals(admin.getId(), temp.getId())) {
            return fail("昵称[" + admin.getNickname() + "]已存在");
        }
        Boolean modifyPwd = getParaToBool("modifyPwd", false);
        if (modifyPwd) {
            String password1 = getPara("password1");
            String password2 = getPara("password2");
            if (!ToolPassword.checkPassword(old.getSalt(), old.getPassword(), admin.getPassword())) {
                return fail("原密码不正确");
            }
            if (!equals(password1, password2)) {
                return fail("两次密码不一致");
            }
            admin.setSalt(PasswordEncoder.createSalt(16));
            admin.setPassword(ToolPassword.getEncPassword(admin.getSalt(), admin.getPassword()));
            if (!adminService.updateByPrimaryKey(admin)) {
                return fail();
            }
            //如果修改的是当前登录的账号
            if (equals(getCurrentAdminId(response), admin.getId())) {
                ToolWeb.addCookie(request, response, "", "/", true, ConstantWebContext.cookie_authmark, null, 0);
            }
            return success();
        }
        if (!adminService.updateByPrimaryKey(admin)) {
            return fail("修改失败");
        }
        return success();
    }

    /**
     * 删除
     */
    @RequestMapping("delete")
    public @ResponseBody
    JsonResult delete() {
        String[] ids = StringUtils.split(getPara("ids"), ",");
        if (ids == null || ids.length == 0) {
            return fail("请选择要删除的数据");
        }
        for (String id : ids) {
            if (equals(id, "1")) {
                return fail("[admin]不可删除!");
            }
            adminService.deleteByPrimaryKey(Long.valueOf(id));
        }
        return success();
    }

    /**
     * 设置用户分组
     */
    public @ResponseBody
    JsonResult setGroup() {
        Long id = getParaToLong("id");
        String groupIds = getPara("groupIds");
        Admin admin = adminService.selectByPrimaryKey(id);
        admin.setGroupIds(groupIds);
        adminService.updateByPrimaryKey(admin);
        return success();
    }

    /**
     * 禁用
     */
    public @ResponseBody
    JsonResult lock() {
        Admin admin = adminService.selectByPrimaryKey(getParaToLong("id"));
        if (admin != null && !admin.getLocked()) {
            admin.setLocked(true);
            if (!adminService.updateByPrimaryKey(admin)) {
                return fail("禁用失败,请重试");
            }
            return success();
        }
        return fail("用户不存在或已被禁用");
    }

    /**
     * 解禁
     */
    public @ResponseBody
    JsonResult unlock() {
        Admin admin = adminService.selectByPrimaryKey(getParaToInt("id"));
        if (admin != null && admin.getLocked()) {
            admin.setLocked(false);
            if (adminService.updateByPrimaryKey(admin)) {
                return fail("禁用失败,请重试");
            }
            return success();
        }
        return fail("用户不存在或已解除禁用");
    }
}